package controller

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"web_app/dao/mysql"
	"web_app/logic"
	"web_app/modules"
	"web_app/pkg/jwt"
)

func SignUpHandler(c *gin.Context) {
	var p modules.ParamSignUp
	if err := c.ShouldBindJSON(&p); err != nil {
		zap.L().Error("SignUp 参数有误", zap.Error(err))

		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			ResponseError(c, CodeInvalidParam)
			return
		}

		ResponseErrorWithMsg(c, CodeInvalidParam, removeTopStruct(errs.Translate(trans)))

		return
	}
	if err := logic.SignUp(&p); err != nil {
		zap.L().Error("注册失败", zap.Error(err))
		if errors.Is(err, mysql.ErrorUserExist) {
			ResponseError(c, CodeUserExist)
			return
		}
		ResponseError(c, CodeServerBusy)

		return
	}

	ResponseSuccess(c, nil)
}

func LoginHandler(c *gin.Context) {
	var p modules.ParamLogin
	var resultUser *modules.User
	var err error
	if err := c.ShouldBindJSON(&p); err != nil {
		zap.L().Error("Login 参数有误", zap.Error(err))
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Login请求参数有误", zap.Error(err))
			ResponseError(c, CodeInvalidParam)
			return
		}
		ResponseErrorWithMsg(c, CodeInvalidParam, removeTopStruct(errs.Translate(trans)))
		return
	}

	//接收好参数开始登陆验证
	if err, resultUser = logic.Login(&p); err != nil {
		zap.L().Error("登陆出错", zap.Error(err))
		if errors.Is(err, mysql.ErrorPassword) {
			ResponseError(c, CodeInvalidPassword)
			return
		} else if errors.Is(err, mysql.ErrorUserNotExist) {
			ResponseError(c, CodeUserNotExist)
			return
		}
		return
	}

	token, err := jwt.GenToken(resultUser.UserID, resultUser.Username)

	ResponseSuccess(c, token)
	return
}
